const fs = require("node:fs");
const path = require("node:path");

const projectMapper = require("../mapper/projectMapper.js");
const itemMapper = require("../mapper/itemMapper.js");
const {db} = require("../db/db");

function add(entity) {
    return new Promise((resolve, reject) => { 
        if (!entity.cId || !entity.name) {
            reject("parameter error")
            return;
        }
       
        projectMapper.addProject(entity, function (err){
            if (err) { reject(err); return; }
            resolve(this.lastID)
        })
    })  
}
exports.add = add

function get(entityId) {
    return new Promise((resolve, reject) => {
        projectMapper.selectProjectById(entityId, (err, entity) => {
            if (err != null) { reject(err); return; }
            resolve(entity);
        })
    })
}
exports.get = get

function getAll() {
    return new Promise((resolve, reject) => {
        projectMapper.selectAllProject((err, entities) => {
            if (err != null) { reject(err); return; }
            resolve(entities);
        })
    })
}
exports.getAll = getAll

function deleteEntity(entityId) {
    return new Promise((resolve, reject) => {
        if (!entityId) {
            reject("parameter error")
            return;
        }
        
        db.serialize(() => {
            db.run("begin");
    
            itemMapper.deleteItemsByProjectId(entityId, (err) => {
                if (err) { reject(err); return; }
            })
    
            projectMapper.deleteProjectById(entityId, (err) => {
                if (err) { reject(err); return; }
                resolve()
            })
            
            db.run("commit");
        })
    })
}
exports.delete = deleteEntity

function update(entity) {
    return new Promise((resolve, reject) => { 
        if (!entity.id || !entity.name) {
            reject("parameter error")
            return;
        }
        
        projectMapper.updateProject(entity, (err) => {
            if (err) { reject(err); return; }
            resolve()
        })
    })  
}
exports.update = update


function saveAllProjects() { 
    return new Promise((resolve, reject) => {
        projectMapper.selectAllProject((err, rows) => {
            if (err) {
                reject(err);
                return
            }
       
            var writer = fs.createWriteStream(path.join(__dirname, "../../core/static/js2/project.js"));
            writer.write("var _projects = ");
            writer.write(JSON.stringify(rows));
            writer.end(';');
    
            resolve()
        })
    })
}
exports.saveAllProjects = saveAllProjects


